package ru.bragnikita.utils.logexplorer.web;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.bragnikita.utils.logexplorer.logic.FileDownloadException;
import ru.bragnikita.utils.logexplorer.logic.FileSystemInterface;
import ru.bragnikita.utils.logexplorer.model.FileWithContent;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Nikita.Brazhnikov
 */
@WebServlet(name = "GetFileServlet", urlPatterns = {"/get/*"})
public class GetFileServlet extends HttpServlet {

	private static final Logger logger = LoggerFactory.getLogger(GetFileServlet.class);

	@Inject
	private FileSystemInterface fileSystem;

	protected void doPost(HttpServletRequest request,
	                      HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doGet(HttpServletRequest request,
	                     HttpServletResponse response) throws ServletException, IOException {
		final String fileParam = request.getParameter("file");
		if (StringUtils.isEmpty(fileParam)) {
			logger.warn("No file name provided");
		} else {
			logger.info("Request for content of {}", fileParam);
			InputStream is = null;
			try {
				final FileWithContent fileContent = fileSystem.getFileContent(fileParam);
				if ("text".equals(request.getParameter("type") + ""))
					response.setContentType("text/plain");
				if ("download".equals(request.getParameter("view") + ""))
					response.setHeader("Content-disposition", "attachment; filename=" + fileContent.getFileName());
				final String encoding = request.getParameter("encoding");
				if (StringUtils.isNotBlank(encoding)) {
					response.setCharacterEncoding(encoding);
				}
				is = fileContent.getContentStream();
				IOUtils.copy(is, response.getOutputStream());
				response.getOutputStream().flush();
			} catch (FileDownloadException e) {
				logger.error("Request file content error", e);
			} finally {
				IOUtils.closeQuietly(is);
			}
		}
	}

	private String getVerifiedEncodingString(HttpServletRequest request) {
		String encoding = request.getParameter("encoding");
		if (StringUtils.isNotBlank(encoding)) {
			return encoding;
		} else
			return null;
	}
}
